<template>
  <view class="new-or-edit-modal">
    <up-popup v-model:show="show" overlay mode="bottom" touchable maxHeight="'80%'" closeable closeOnClickOverlay
      @close="close" @open="open">
      <view class="modal-content">
        <view class="modal-header">
          <view class="modal-title">指派任务</view>
        </view>
        <!-- uview-plus的表单，包含标题，公告内容，单选是否弹窗推送，状态下拉，确认按钮 -->
        <up-form labelPosition="left" :model="formModel" :rules="rules" ref="formRef">
          <up-form-item labelWidth="100" label="巡检员" prop="accountIds">
            <view class="inspector-select" @click="showInspectorPicker = true">
              <text v-if="selectedInspectorNames">{{ selectedInspectorNames }}</text>
              <text v-else class="placeholder">请选择巡检员</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
          </up-form-item>
          <up-form-item labelWidth="100" label="备注" prop="dealRemark">
            <up-input v-model="formModel.dealRemark" placeholder="请输入备注" />
          </up-form-item>
        </up-form>
      </view>

      <view class="modal-footer">
        <up-button type="primary" @click="submit" :loading="loading">确认</up-button>
      </view>
    </up-popup>

    <!-- 巡检员选择器 -->
    <up-picker 
      keyName="accountName"
      valueName="accountId"
      :show="showInspectorPicker" 
      :columns="[inspectorColumns]" 
      :closeOnClickOverlay="true"
      @confirm="handleInspectorConfirm" 
      @cancel="showInspectorPicker = false" 
      @close="showInspectorPicker = false"
      multiple
    ></up-picker>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { assignInspector, getInspectorList } from '@/api';

const props = defineProps({
  rowData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["confirm", "cancel"]);

defineOptions({
  name: "ApplyModal",
});

const show = defineModel("show", { type: Boolean, default: false });
const formRef = ref();
const loading = ref(false);
const showInspectorPicker = ref(false);
const inspectorList = ref<any[]>([]);
const selectedInspectors = ref<any[]>([]);

// 计算选中的巡检员名称，用于显示
const selectedInspectorNames = computed(() => {
  if (selectedInspectors.value.length === 0) return '';
  return selectedInspectors.value.map(item => item.accountName).join(', ');
});

// 计算选中的巡检员ID，用于提交
const selectedInspectorIds = computed(() => {
  if (selectedInspectors.value.length === 0) return '';
  return selectedInspectors.value.map(item => item.accountId).join(',');
});

// 巡检员选择器数据
const inspectorColumns = computed(() => {
  const filteredList = inspectorList.value.filter(item => item.status === 0)
  console.log('过滤后的巡检员列表:', filteredList);
  
  return filteredList
});

// 获取巡检员列表
const fetchInspectorList = async () => {
  try {
    const res = await getInspectorList();
    if (res.success && Array.isArray(res.data)) {
      inspectorList.value = res.data;
      console.log('巡检员列表数据:', inspectorList.value);
    }
  } catch (error) {
    console.error('获取巡检员列表失败', error);
    uni.showToast({
      title: '获取巡检员列表失败',
      icon: 'error'
    });
  }
};

// 处理巡检员选择确认
const handleInspectorConfirm = (e: any) => {
  selectedInspectors.value = e.value;
  formModel.value.accountIds = selectedInspectorIds.value;
  showInspectorPicker.value = false;
};

const createDefaultModel = () => {
  return {
    bizCode: "",
    accountIds: "",
    dealRemark: "",
  };
};

const formModel = ref(createDefaultModel());

const rules = {
  accountIds: [
    {
      required: true,
      message: "请选择巡检员",
      trigger: ["blur", "change"],
    },
  ],
  dealRemark: [
    {
      required: true,
      message: "请输入备注",
      trigger: ["blur", "change"],
    },
  ],
};

const submit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    formModel.value.bizCode = props.rowData.bizCode;
    const res = await assignInspector(formModel.value);
    if (res.success) {
      uni.showToast({
        title: "指派成功",
        icon: "success",
      });
      emit("confirm");
      show.value = false;
    } else {
      uni.showToast({
        title: res.msg || "指派失败",
        icon: "error",
      });
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};

const open = (item: any) => {
  formModel.value = createDefaultModel();
  selectedInspectors.value = [];
  if (item) {
    formModel.value.bizCode = item.bizCode;
  }
  // 获取巡检员列表
  fetchInspectorList();
};

const close = () => {
  formModel.value = createDefaultModel();
  selectedInspectors.value = [];
  emit("cancel");
};

// 初始化时获取巡检员列表
onMounted(() => {
  fetchInspectorList();
});
</script>

<style lang="scss" scoped>
.new-or-edit-modal {
  .modal-content {
    padding: 20rpx;
  }

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
    }
  }

  .modal-footer {
    padding: 20rpx;
    display: flex;
    justify-content: center;
  }

  .inspector-select {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 70rpx;
    padding: 0 20rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;

    .placeholder {
      color: #999;
    }
  }
}
</style>
